package com.faiz.generic;

import java.util.Arrays;
import java.util.List;
import java.util.Optional;

public class GenericTest {

    public static <T, U> Optional<T> safeCast(Class<T> clazz, U object) {
        if (clazz.isInstance(object)) {
            return Optional.of((T) object);
        } else {
            return Optional.empty();
        }
    }

    //只读方法
    public static int sum1(List<? extends Integer> list) {
        int res = 0;
        for (Integer num : list) {
            res += num;
        }
        return res;
    }

    public static <T extends Integer> int sum(List<T> list) {
        int res = 0;
        for (Integer num : list) {
            res += num;
        }
        return res;
    }

    public static void main(String[] args) {
        Integer[] nums = {1, 2, 3, 4, 5};
        List<Integer> list = Arrays.asList(nums);
        System.out.println(sum(list));
    }
}
